//
//  OffersDetailiewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 8/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "OffersDetailiewController.h"
#import <QuartzCore/QuartzCore.h>
#import "VoucherViewController.h"

@implementation OffersDetailiewController

@synthesize data,myCell,lblIntro1,lblIntro2;
@synthesize offerId = _offerId;

#pragma mark Action

-(void)done:(id)sender
{
    
}
-(IBAction)redeemPressed:(id)sender
{
    VoucherViewController *vVC = [[VoucherViewController alloc]initWithNibName:@"VoucherViewController" bundle:nil];
    vVC.data = self.data;
    [self.navigationController pushViewController:vVC animated:YES];
    [vVC release];
    /*
    double distance;
    if (![[data objectForKey:@"distance"] isKindOfClass:[NSNull class]]) {
        distance = [[data objectForKey:@"distance"] doubleValue];
    }
    if (distance > 50) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                        message:@"You need to be in the proximity of the venue to redeem this voucher." 
                                                       delegate:self 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    if (distance >0 && distance < 50 ) {
        //Done somethings...
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                        message:@"You need to be in the proximity of the venue to redeem this voucher." 
                                                       delegate:self 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
         
    }
    */
}
-(void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(void)activeRedeem 
{
   
    double lat_degrees ;
    double lon_degrees;
    if (![[data objectForKey:@"lat"] isKindOfClass:[NSNull class]]) {
        lat_degrees = [[data objectForKey:@"lat"] doubleValue];
    }
    if (![[data objectForKey:@"lon"] isKindOfClass:[NSNull class]]) {
        lon_degrees = [[data objectForKey:@"lon"] doubleValue];
    }
    CLLocation *location = [[CLLocation alloc] initWithLatitude:lat_degrees longitude:lon_degrees];
    
    
    NSString *lat;
    NSString *lon;
    lat = [JGoUtility sharedLatitude];
    lon = [JGoUtility sharedLongitude];
    double lat_me ;
    double lon_me;
    lat_me = [lat doubleValue] ;
    lon_me = [lon doubleValue];
    
    CLLocation *me = [[CLLocation alloc] initWithLatitude:lat_me longitude:lon_me];
    
    float target = [me distanceFromLocation:location];
    
    if (target < 100.0) {
        redeemUI.hidden = NO;
    }else {
        redeemUI.hidden = YES;
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    if (self.data != nil && _offerId == nil) {
        [self activeRedeem];
    }
    else {
        [JGoUtility showProgressInView:self.view
                                target:self
                                 title:@"Loading..." selector:@selector(delayLoadOffer:)];
    }    
    
    
    lblIntro2.textColor = [UIColor colorWithRed:0. green:0.678 blue:0.941 alpha:1];
    lblIntro1.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];

    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    [self.navigationItem setHidesBackButton:NO];
    
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"info-icon" 
                                 target:self 
                                 action:@selector(done:)];

    [self setTitle:@"Offer Details"];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void) dealloc
{
    [self.data release];
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark Table Delegete
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return (data ? 2 : 0);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else
    {
        return 3;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        return 94;
    }
    return 44;
}

/*
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 44;
    }
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
    if (section == 0) {
        UILabel *lblText = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 40)];
        lblText.text = @"   Nearby";
        lblText.font = [UIFont systemFontOfSize:14];
        lblText.backgroundColor = [UIColor clearColor];
        lblText.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
        
        [lblText sizeToFit];
        return [lblText autorelease];
    }
    return nil;
}
 */
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell;

        
    static NSString *OfferDetailCellIdentifier = @"OfferDetailCell";
    cell = [tableView dequeueReusableCellWithIdentifier:OfferDetailCellIdentifier];
    if (cell == nil) {
       cell  = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:OfferDetailCellIdentifier] autorelease];
       [[NSBundle mainBundle] loadNibNamed:@"OfferDetailCell" owner:self options:nil];
       cell = myCell;
       self.myCell = nil;  
    }
    UIImageView *icon = (UIImageView *)[cell viewWithTag:1];
    UILabel *lbl1 = (UILabel *)[cell viewWithTag:2];
    UILabel *lbl2 = (UILabel *)[cell viewWithTag:3];
    
    if (indexPath.section == 0)
    {
        cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        icon.image = [UIImage imageNamed:@"offers-icon.png"];
        lbl1.hidden = YES;
        lbl2.hidden = YES;
        CGRect tempRec = icon.frame;
        tempRec.origin = CGPointMake(icon.frame.origin.x + 10 + icon.frame.size.width, 0);
        tempRec.size = CGSizeMake(cell.frame.size.width - 10 -icon.frame.origin.x - icon.frame.size.width, cell.frame.size.height - 5*2);
        UIWebView *myWebView = [[UIWebView alloc]initWithFrame:tempRec];
        NSString *content = [NSString stringWithFormat:@"<span style=\'color: #00AFEB;\'>-%@ OFF</span> <span style=\'color: #AAAAAA;\'>%@ at %@. </span> ",[data valueForKey:@"discount"],[data valueForKey:@"title"],[data valueForKey:@"shop_name"]]; 
        [myWebView loadHTMLString:content baseURL:nil];
        [myWebView sizeToFit];
        
        myWebView.backgroundColor = [UIColor clearColor];
        myWebView.opaque = NO;

        [cell addSubview:myWebView];
        [myWebView release];
    }
    if (indexPath.section == 1) {
        lbl1.textColor = [UIColor colorWithRed:0. green:0.678 blue:0.941 alpha:1];
        lbl2.textColor = [UIColor colorWithRed:0.573 green:0.573 blue:0.573 alpha:1];
        switch (indexPath.row) {
            case 0:
            {
                MKMapView*		mapView;
                mapView = [[MKMapView alloc]initWithFrame:CGRectMake(10, 1, 300, 93)];
                mapView.showsUserLocation=TRUE;
                mapView.mapType=MKMapTypeStandard;	
                mapView.layer.cornerRadius = 10.0;
                /*Region and Zoom*/	
                MKCoordinateRegion region;
                MKCoordinateSpan span;
                span.latitudeDelta = 0.01;
                span.longitudeDelta = 0.01;
                CLLocationCoordinate2D location; //mapView.userLocation.coordinate;
                if (![[data objectForKey:@"lat"] isKindOfClass:[NSNull class]]) {
                    location.latitude = [[data objectForKey:@"lat"] doubleValue];
                }
                if (![[data objectForKey:@"lon"] isKindOfClass:[NSNull class]]) {
                    location.longitude = [[data objectForKey:@"lon"] doubleValue];
                }
                //location.latitude = placeInfo.latitude;
                //location.longitude = placeInfo.longitude;
                region.span = span;
                region.center = location;
                [mapView regionThatFits:region]; 
                
                CLLocationDegrees minLatitude = 90;
                CLLocationDegrees maxLatitude = -90;
                CLLocationDegrees minLongitude = 180;
                CLLocationDegrees maxLongitude = -180;
                
                if (location.latitude > maxLatitude && location.latitude < minLatitude && location.longitude >maxLongitude && location.longitude < minLongitude ) {
                    [mapView setRegion:region animated:TRUE];
                }
                 MyAnnotation *anno = [[MyAnnotation alloc] initWithCoords:location name:@""];
                [mapView addAnnotation:anno];
                [cell addSubview:mapView];
                //[mapView release];
                break;
            }
            case 1:
            {
                icon.image = [UIImage imageNamed:@"time-icon.png"];
                lbl1.text = @"Valid:";
                if (![[data objectForKey:@"valid_time"] isKindOfClass:[NSNull class]]) {
                    lbl2.text = [data objectForKey:@"valid_time"];
                }
                
                break; 
            }
            case 2:
            {
                icon.image = [UIImage imageNamed:@"date-icon.png"];
                lbl1.text = @"Expires:";
                
                if (![[data objectForKey:@"expired_time"] isKindOfClass:[NSNull class]]) {
                    lbl2.text = [data objectForKey:@"expired_time"];
                }
                
                break; 
            }
   
                
            default:
                break;
        }
        
    }
    
    return cell;    
}

#pragma Delay Method

- (void)delayLoadOffer:(MBProgressHUD*)progress
{
    NSDictionary *user = [JGoUtility sharedCreateAccount];
    NSString *userId = [user objectForKey:@"user_id"];
    NSError *error = nil;

    NSDictionary *offer = [JGoAPI getOfferDetailWithUserId:userId offerId:self.offerId error:&error];
    
    if (!error) {
        self.data = offer;
        [self activeRedeem];
        [self.tableView reloadData];
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
}

@end
